package com.ds.dsm.view.config.tree;

import com.ds.common.JDSException;
import com.ds.config.ListResultModel;
import com.ds.enums.db.MethodChinaName;
import com.ds.esd.custom.annotation.GridViewAnnotation;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.bean.ApiClassConfig;
import com.ds.esd.custom.bean.MethodConfig;
import com.ds.esd.custom.bean.nav.NavBaseViewBean;
import com.ds.esd.custom.enums.CustomMenuItem;
import com.ds.esd.custom.module.annotation.ModuleAnnotation;
import com.ds.esd.custom.tree.CustomTreeViewBean;
import com.ds.esd.custom.tree.enums.CustomTreeEvent;
import com.ds.esd.dsm.DSMFactory;
import com.ds.web.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/dsm/view/config/tree/event/")
public class ViewTreeEventService {


    @MethodChinaName(cname = "监听事件")
    @RequestMapping(method = RequestMethod.POST, value = "BindMenus")
    @GridViewAnnotation
    @ModuleAnnotation(imageClass = "spafont spa-icon-c-statusbutton", caption = "监听事件")
    @APIEventAnnotation(autoRun = true, bindMenu = CustomMenuItem.treeNodeEditor)
    @ResponseBody
    public ListResultModel<List<TreeEventView>> getBindMenus(String sourceClassName, String domainId, String viewInstId, String sourceMethodName) {
        ListResultModel<List<TreeEventView>> resultModel = new ListResultModel<>();
        try {
            ApiClassConfig customESDClassAPIBean = DSMFactory.getInstance().getAggregationManager().getApiClassConfig(sourceClassName, domainId);
            MethodConfig methodAPIBean = customESDClassAPIBean.getMethodByName(sourceMethodName);
            CustomTreeViewBean customTreeViewBean = null;
            if (methodAPIBean.getView() instanceof NavBaseViewBean) {
                NavBaseViewBean baseViewBean = (NavBaseViewBean) methodAPIBean.getView();
                customTreeViewBean = baseViewBean.getTreeView();
            } else if (methodAPIBean.getView() instanceof CustomTreeViewBean) {
                customTreeViewBean = (CustomTreeViewBean) methodAPIBean.getView();
            }
            Set<CustomTreeEvent> events = customTreeViewBean.getEvent();
            List<TreeEventView> views = new ArrayList<>();
            for (CustomTreeEvent gridEvent : events) {
                views.add(new TreeEventView(gridEvent, methodAPIBean));
            }
            resultModel = PageUtil.getDefaultPageList(views);

        } catch (JDSException e) {
            e.printStackTrace();
        }
        return resultModel;
    }


}
